// utils/request.ts

import axios from 'axios';
import type { AxiosRequestConfig, AxiosInstance, AxiosResponse, AxiosError } from 'axios';

const apiClient: AxiosInstance = axios.create({
    baseURL: '/api',
    // timeout: 10000,
});

interface MyRequestConfig {
    method: 'get' | 'post' | 'put' | 'delete';
    url: string;
    data?: any;
    headers?: Record<string, string>;
    token?: boolean;
}

function errorHandling(error: AxiosError) {
    console.error('请求出错', error);
    if (error.response) {
        console.error(`Error Status: ${error.response.status}`);
        console.error('Error Data:', error.response.data);
    } else if (error.request) {
        console.error('No response received:', error.request);
    } else {
        console.error('Request setup error:', error.message);
    }
}

export function request<T = any>(config: MyRequestConfig): Promise<T> {
    if (!config.method || !config.url) {
        return Promise.reject(new Error('配置出错，url 或者 method 为空。'));
    }

    const axiosConfig: AxiosRequestConfig = {
        method: config.method,
        url: config.url,
        withCredentials: !!config.token,
    };

    if (config.headers) {
        axiosConfig.headers = config.headers;
    }

    if (config.method === 'get') {
        axiosConfig.params = config.data;
    } else if (['post', 'put', 'delete'].includes(config.method)) {
        axiosConfig.data = config.data;
    } else {
        return Promise.reject(new Error('不支持的请求方法。'));
    }

    return apiClient.request<T>(axiosConfig)
        .then((res: AxiosResponse<T>) => {
            return res.data; // 直接返回后端原始数据
        })
        .catch((err: AxiosError) => {
            errorHandling(err);
            return Promise.reject(err); // 将错误继续抛出，由调用方处理
        });
}
